package com.minshenglife.zanzan.web.weixin;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.minshenglife.commons.dal.Page;
import com.minshenglife.commons.security.utils.AccessTokenUtils;
import com.minshenglife.commons.security.utils.pp.UserIdentify;
import com.minshenglife.commons.security.utils.pp.UserIdentify.UserType;
import com.minshenglife.zanzan.entity.EMOUserGroup;
import com.minshenglife.zanzan.entity.EndPlate;
import com.minshenglife.zanzan.entity.MailBox;
import com.minshenglife.zanzan.entity.RedFlower;
import com.minshenglife.zanzan.entity.User;
import com.minshenglife.zanzan.entity.eoa.LA_AGENT;
import com.minshenglife.zanzan.entity.eoa.V_EMP;
import com.minshenglife.zanzan.pub.Keys;
import com.minshenglife.zanzan.pub.message.MessageUtil;
import com.minshenglife.zanzan.pub.message.WXRespMessage;
import com.minshenglife.zanzan.pub.message.custservice.CS_TextMessage;
import com.minshenglife.zanzan.pub.utils.Message;
import com.minshenglife.zanzan.pub.utils.WXKeys;
import com.minshenglife.zanzan.result.EndPlateResult;
import com.minshenglife.zanzan.result.RuleHelp;
import com.minshenglife.zanzan.service.AccessTokenService;
import com.minshenglife.zanzan.service.AgentService;
import com.minshenglife.zanzan.service.EMOUserGroupService;
import com.minshenglife.zanzan.service.EMOUserService;
import com.minshenglife.zanzan.service.EndPlateService;
import com.minshenglife.zanzan.service.MailBoxService;
import com.minshenglife.zanzan.service.RedFlowerService;
import com.minshenglife.zanzan.service.ReviewService;
import com.minshenglife.zanzan.service.RuleService;
import com.minshenglife.zanzan.service.UserService;
import com.minshenglife.zanzan.service.VEmpService;
import com.minshenglife.zanzan.web.weixin.form.BindForm;
import com.minshenglife.zanzan.web.weixin.form.CommonDataForm;
import com.minshenglife.zanzan.web.weixin.form.StatForm;
import com.minshenglife.zanzan.web.weixin.model.WXUserInfo;
import com.minshenglife.zanzan.web.weixin.result.UserResult;
import com.minshenglife.zanzan.web.weixin.service.EMOWXBaseServcie;
import com.minshenglife.zanzan.web.weixin.service.WXAccTokenService;
import com.minshenglife.zanzan.web.weixin.service.WXBaseService;
import com.nationsky.pub.utils.StringUtils;


/**
 * 微信EMO
 * @author jianghaibo
 * 
 */
@Controller
@RequestMapping("/emouser")
public class EMOUserController extends BaseController {
	Logger log = LoggerFactory.getLogger(EMOUserController.class);
	@Resource
	EMOUserService emoUserService;
	@Resource
	EMOUserGroupService emoUserGroupService;
	@Resource
	AgentService agentService;
	@Resource
	VEmpService empService;
	@Resource
	AccessTokenService accessTokenService;
	@Resource
	WXAccTokenService tokenService;
    
    
    /**
     * 绑定员工号
     * @param request
     * @param response
     * @param bindForm
     * @return
     */
    @RequestMapping(value="/bindEmpNo.do",method=RequestMethod.POST)
    @ResponseBody
    public String bindEmpNo(HttpServletRequest request, HttpServletResponse response,
    		BindForm bindForm){
    	log.debug("start bindEmpNo method ");
    	Message message=null;
    	try {
    		log.debug("BindForm attrubit：empNo-->"+bindForm.getEmpNo()+",idNo-->"+bindForm.getIdNo()+",openid-->"+bindForm.getOpenId()+",appid-->"+bindForm.getAppid());
    		String openId=super.getOpenId(request);
    		log.debug("当前绑定人的openId："+openId);
    		String appid=super.getAppid(request);
			log.debug("当前绑定人的appidId："+appid);
    		//校验用户信息是否正确
    		message=checkBindInfo(bindForm);
    		log.debug("校验用户信息是"+message.toString());
			if(message != null && Message.STATE_200.equals(message.getState())){
				String idNo = "";
				
				//校验该员工号是否已经绑定
				log.debug("开始--校验该员工号是否已经绑定");
				boolean isBind=emoUserGroupService.isBind(bindForm.getEmpNo(),openId);
				if(!isBind){
					log.debug("开始绑定员工");
					emoUserGroupService.bind(openId,bindForm.getAppid(),message.getData());
					String token = tokenService.getEMOWXAccToken();
					//{"openid":"oDF3iYx0ro3_7jD4HFRDfrjdCM58","to_groupid":108}
					//拼装用户分组json
					JSONObject json = new JSONObject();
					json.put("openid", openId);
					
					try {
						//推送客服消息，告知用户已经绑定成功
						String userName = "";
						Map map = (Map) message.getData();
						String empType = (String) map.get("type");
						if(empType.equals("1")){	//如果是内勤
							V_EMP emp = (V_EMP) map.get("user");
							userName = emp.getEmpName();
							idNo = emp.getIdNo();
							json.put("to_groupid", 103);
						}else if(empType.equals("2")){	//如果是外勤
							LA_AGENT emp = (LA_AGENT) map.get("user");
							userName = emp.getName();
							idNo = emp.getIdNo();
							json.put("to_groupid", 104);
						}
						//移动用户分组
						boolean removeUserGroupIsSuccuss = EMOWXBaseServcie.removeUserGroup(json.toString(), token);
						if(removeUserGroupIsSuccuss){
							log.info("移动用户分组成功");
						}else{
							log.info("移动用户分组失败,重新分组");
							while(!removeUserGroupIsSuccuss){
								removeUserGroupIsSuccuss = EMOWXBaseServcie.removeUserGroup(json.toString(), token);
							}
						}
						
						String to_message = userName+"您好，欢迎加入民生保险CMO在线！";
						CS_TextMessage tm=new CS_TextMessage();
						tm.setTouser(openId);
						tm.setMsgtype(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
						tm.setText(to_message);
						WXRespMessage respMessage=WXBaseService.sendCustServiceMessage(tm,tokenService.getEMOWXAccToken());
						log.info("==========="+respMessage.getErrcode());
						System.out.println("==========="+respMessage.getErrcode());
						if("0".equals(respMessage.getErrcode())){
							log.info("客服消息发送成功");
						}else{
							log.info("客服消息发送失败，错误信息："+respMessage.getErrmsg());
						}
					} catch (Exception e) {
						log.info("客服消息发送失败");
						e.printStackTrace();
					}
					
					//创建用户访问token，建立访问失效
					String access_token=AccessTokenUtils.newToken(new UserIdentify(UserType.weixin,openId), idNo);
					User user = new User();
					user.setWXCode(openId);
					user.setEmpId(bindForm.getEmpNo());
					accessTokenService.insertAccessToken(user,access_token);//插入页面时效
					message=new Message(Message.STATE_200,access_token);
				}else{
					log.debug("{"+bindForm.getEmpNo()+"}该员工号已经绑定");
					message=new Message(Message.STATE_one,"亲，该员工号已被绑定，请使用自己的工号，如有疑问请联系系统管理员！");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			message=new Message(Message.STATE_one,"服务器异常");
		}
    	log.debug("end bindEmpNo method ; return message : "+message);
        return message.toString();
    }
    /**
     * 解除绑定员工号
     * @param request
     * @param response
     * @param bindForm
     * @return
     */
    @RequestMapping(value="/empUnbound.do")
    @ResponseBody
    public void empUnbound(HttpServletRequest request, HttpServletResponse response){
    	log.debug("start empUnbound method ");
    	try {
    		String empId = super.getEmpId(request);
    		String opendid = super.getOpenId(request);
			log.debug("当前绑定人的empId："+empId);
    		//解除绑定
			emoUserGroupService.EmpUnbound(empId,opendid);
			//跳转至解绑成功页面
			log.debug(WXKeys.WX_BASEURL+"/jsp/success/success.jsp");
			response.sendRedirect(WXKeys.WX_BASEURL+"/jsp/success/success.jsp");
		} catch (Exception e) {
			e.printStackTrace();
			try {
				response.sendRedirect(WXKeys.WX_BASEURL+"/jsp/error/error.jsp");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
    	log.debug("end empUnbound method ");
    }
    
    /**
     * 校验用户信息是否正确
     * @param bindForm
     * @return
     */
    private Message checkBindInfo(BindForm bindForm) {
    	Message message=new Message(Message.STATE_200);
    	Map<String, Object> map = new HashMap<String, Object>();
    	if(bindForm == null || StringUtils.isNullOrEmpty(bindForm.getEmpNo()) || StringUtils.isNullOrEmpty(bindForm.getIdNo()) || StringUtils.isNullOrEmpty(bindForm.getAppid())){
    		message=new Message(Message.STATE_one,"信息有误请确认");
    	}else{
	    	V_EMP emp = empService.findByCodeAndIdno(bindForm.getEmpNo(), bindForm.getIdNo());
	    	if(emp != null){
	    		map.put("type", "1");	//内勤员工
	    		map.put("user", emp);
	    		message.setData(map);
	    	}else{
	    		LA_AGENT agent = agentService.findByCodeAndIdno(bindForm.getEmpNo(), bindForm.getIdNo());
	    		if(agent != null){
	    			map.put("type", "2");	//外勤员工
		    		map.put("user", agent);
		    		message.setData(map);
	    		}else{
	    			message=new Message(Message.STATE_one,"该员工不存在");
	    		}
	    	}
    	}
		return message;
	}

    public static void main(String[] sdf){
		System.out.println("sadfd".substring(0, 1));
	}
   
}
